package org.thinkinbunny.financial.view;

import java.util.Calendar;

import org.thinkinbunny.financial.R;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

public class ChooseDateDialogActivity extends Activity {

	private DatePicker dPicker;

	private TimePicker tPicker;

	private TextView tTextView;

	// 声明时间变量

	private int mYear;

	private int mMonth;

	private int mDay;

	private int mHour;

	private int mMinute;

	private Calendar calendar;

	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.choose_date);

		/* 取得当前日期与时间 */

		calendar = Calendar.getInstance();

		mYear = calendar.get(Calendar.YEAR);

		mMonth = calendar.get(Calendar.MONTH);

		mDay = calendar.get(Calendar.DAY_OF_MONTH);

		mHour = calendar.get(Calendar.HOUR_OF_DAY);

		mMinute = calendar.get(Calendar.MINUTE);

		tTextView = (TextView) findViewById(R.id.tTextView);

		tTextView.setTextColor(Color.RED);

		updateTime();

		dPicker = (DatePicker) findViewById(R.id.dPicker);

		tPicker = (TimePicker) findViewById(R.id.tPicker);

		tPicker.setIs24HourView(true); // 时间设为24小时制

		/* 当日期改变时，tTextView的日期也改变 */

		dPicker.init(mYear, mMonth, mDay,
				new DatePicker.OnDateChangedListener() {

					@Override
					public void onDateChanged(DatePicker view, int year,

					int monthOfYear, int dayOfMonth) {

						// TODO Auto-generated method stub

						mYear = year;

						mMonth = monthOfYear;

						mDay = dayOfMonth;

						updateTime();

					}

				});

		/* 当时间改变时，tTextView的时间也改变 */

		tPicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

			@Override
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

				// TODO Auto-generated method stub

				mHour = hourOfDay;

				mMinute = minute;

				updateTime();

			}

		});

	}

	/* 更新时间 */

	private void updateTime() {

		tTextView.setText(

		new StringBuilder().append(mYear).append("-")

		.append(formateTime(mMonth + 1)).append("-")

		.append(formateTime(mDay)).append(" ")

		.append(formateTime(mHour)).append(":")

		.append(formateTime(mMinute))

		);

	}

	/* 时间格式 */

	private String formateTime(int time) {

		String timeStr = "";

		if (time < 10)

			timeStr = "0" + String.valueOf(time);

		else

			timeStr = String.valueOf(time);

		return timeStr;

	}

}